feat: add licenses.validate endpoint to preview a license before applying#40858
feat: add licenses.validate endpoint to preview a license before applying#40858rodrigok wants to merge 2 commits into
Conversation
…ying Adds a new `POST /api/v1/licenses.validate` REST endpoint that validates a Rocket.Chat license (V2 or V3 JWT) against the current workspace's validation structure without applying it, so the result can be previewed from the UI before the license is committed. - core-typings: new `LicenseValidationResult` type - license: `LicenseManager.validateLicenseForPreview()` runs the same validation pipeline used on apply (URL, periods, limits) without mutating state or emitting events; the shared `licenseValidationBehaviors` constant is reused by both the apply and preview paths to avoid duplication - rest-typings: `isLicensesValidateProps` schema + endpoint typing - meteor: `licenses.validate` route (edit-privileged-setting) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
Looks like this PR is not ready to merge, because of the following issues:
Please fix the issues and try again If you have any trouble, please check the PR guidelines |
WalkthroughThis PR introduces a ChangesLicense Preview Validation
Sequence DiagramsequenceDiagram
participant Client
participant License as License.validateLicenseForPreview
participant Decrypt as decrypt/normalize
participant Validate as runValidation
participant Cache as shouldPreventActionResultsMap
Client->>License: encrypted license string
License->>Decrypt: decrypt and normalize
Decrypt-->>License: LicenseData
License->>Validate: run with behaviors + prevent_action
Validate->>Cache: check/update action prevention cache
Cache-->>Validate: cached results
Validate-->>License: validation result
License-->>Client: LicenseValidationResult (format, validity, modules, errors)
🎯 3 (Moderate) | ⏱️ ~25 minutes
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
🦋 Changeset detectedLatest commit: 93bc1b7 The changes in this PR will be included in the next version bump. This PR includes changesets to release 4 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## develop #40858 +/- ##
===========================================
- Coverage 70.17% 70.17% -0.01%
===========================================
Files 3341 3341
Lines 123645 123572 -73
Branches 22050 22412 +362
===========================================
- Hits 86765 86711 -54
+ Misses 33539 33504 -35
- Partials 3341 3357 +16
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
ee/packages/license/src/validateLicenseForPreview.spec.ts (1)
3-95: ⚡ Quick winAdd a case that proves preview surfaces exceeded limits.
The implementation now appends
'prevent_action'to the preview behaviors, but this suite never drives a limit over its licensed max and asserts thatvalidationErrorscontains aprevent_actionentry whileisValidstays true. That is the main preview-only branch inee/packages/license/src/license.ts, so it should have explicit coverage.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ee/packages/license/src/validateLicenseForPreview.spec.ts` around lines 3 - 95, Add a new test in the validateLicenseForPreview suite that builds a license via MockedLicenseBuilder which sets a max limit lower than the usage so the preview logic will produce a 'prevent_action' behavior; call licenseManager.validateLicenseForPreview(...) with that license and assert result.isFormatValid is true, result.isValid remains true, and result.validationErrors contains an object with behavior: 'prevent_action' (and appropriate reason), and ensure grantedModules still reflect allowed modules; use validateLicenseForPreview, MockedLicenseBuilder, and licenseManager to locate where to add this case.ee/packages/license/src/license.ts (1)
337-341: ⚡ Quick winAvoid decrypting the preview payload twice.
validateFormat()already verifies/decrypts the license, and this branch immediately callsdecrypt()again before parsing. That doubles the crypto work for every preview request.Suggested fix
let license: ILicenseV3; try { - await validateFormat(encryptedLicense); - const decrypted = JSON.parse(await decrypt(encryptedLicense)); license = encryptedLicense.startsWith('RCV3_') ? decrypted : convertToV3(decrypted); } catch (err) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ee/packages/license/src/license.ts` around lines 337 - 341, The code decrypts the preview payload twice: validateFormat(encryptedLicense) already returns/produces the decrypted payload, but the branch still calls decrypt(encryptedLicense) again; change validateFormat to return the decrypted string/object (or have it return both a boolean and decrypted payload), then replace the second decrypt call with the decrypted value from validateFormat (e.g., const decryptedRaw = await validateFormat(encryptedLicense); const decrypted = JSON.parse(decryptedRaw); license = encryptedLicense.startsWith('RCV3_') ? decrypted : convertToV3(decrypted)), updating function signatures/types for validateFormat if needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ee/packages/license/src/license.ts`:
- Around line 333-361: validateLicenseForPreview currently skips the readiness
guard and calls runValidation on partial workspace state; add the same readiness
check used in setLicense/validateLicense by calling
isReadyForValidation.call(this) before invoking runValidation and, if it returns
false, short-circuit and return a LicenseValidationResult matching the other
guards (e.g., isFormatValid: true/false per existing logic, isValid: false,
workspaceUrl, empty grantedModules and validationErrors) so the preview mirrors
the apply-path readiness behavior; reference validateLicenseForPreview,
isReadyForValidation, runValidation, setLicense and validateLicense when making
the change.
---
Nitpick comments:
In `@ee/packages/license/src/license.ts`:
- Around line 337-341: The code decrypts the preview payload twice:
validateFormat(encryptedLicense) already returns/produces the decrypted payload,
but the branch still calls decrypt(encryptedLicense) again; change
validateFormat to return the decrypted string/object (or have it return both a
boolean and decrypted payload), then replace the second decrypt call with the
decrypted value from validateFormat (e.g., const decryptedRaw = await
validateFormat(encryptedLicense); const decrypted = JSON.parse(decryptedRaw);
license = encryptedLicense.startsWith('RCV3_') ? decrypted :
convertToV3(decrypted)), updating function signatures/types for validateFormat
if needed.
In `@ee/packages/license/src/validateLicenseForPreview.spec.ts`:
- Around line 3-95: Add a new test in the validateLicenseForPreview suite that
builds a license via MockedLicenseBuilder which sets a max limit lower than the
usage so the preview logic will produce a 'prevent_action' behavior; call
licenseManager.validateLicenseForPreview(...) with that license and assert
result.isFormatValid is true, result.isValid remains true, and
result.validationErrors contains an object with behavior: 'prevent_action' (and
appropriate reason), and ensure grantedModules still reflect allowed modules;
use validateLicenseForPreview, MockedLicenseBuilder, and licenseManager to
locate where to add this case.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 99090ac8-bcb3-43ec-88be-d20e32821295
📒 Files selected for processing (7)
.changeset/license-validate-preview.mdapps/meteor/ee/server/api/licenses.tsee/packages/license/src/license.tsee/packages/license/src/validateLicenseForPreview.spec.tspackages/core-typings/src/license/LicenseValidationResult.tspackages/core-typings/src/license/index.tspackages/rest-typings/src/v1/licenses.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: cubic · AI code reviewer
- GitHub Check: Hacktron Security Check
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation
Files:
packages/core-typings/src/license/LicenseValidationResult.tspackages/core-typings/src/license/index.tsapps/meteor/ee/server/api/licenses.tspackages/rest-typings/src/v1/licenses.tsee/packages/license/src/license.tsee/packages/license/src/validateLicenseForPreview.spec.ts
**/*.spec.ts
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.spec.ts: Use descriptive test names that clearly communicate expected behavior in Playwright tests
Use.spec.tsextension for test files (e.g.,login.spec.ts)
Files:
ee/packages/license/src/validateLicenseForPreview.spec.ts
🧠 Learnings (8)
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.
Applied to files:
.changeset/license-validate-preview.md
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.
Applied to files:
packages/core-typings/src/license/LicenseValidationResult.tspackages/core-typings/src/license/index.tsapps/meteor/ee/server/api/licenses.tspackages/rest-typings/src/v1/licenses.tsee/packages/license/src/license.tsee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.
Applied to files:
packages/core-typings/src/license/LicenseValidationResult.tspackages/core-typings/src/license/index.tsapps/meteor/ee/server/api/licenses.tspackages/rest-typings/src/v1/licenses.tsee/packages/license/src/license.tsee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.
Applied to files:
packages/core-typings/src/license/LicenseValidationResult.tspackages/core-typings/src/license/index.tsapps/meteor/ee/server/api/licenses.tspackages/rest-typings/src/v1/licenses.tsee/packages/license/src/license.tsee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-05-11T23:14:59.316Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 40469
File: packages/rest-typings/src/v1/users.ts:337-337
Timestamp: 2026-05-11T23:14:59.316Z
Learning: In Rocket.Chat REST endpoint typings (e.g., packages/rest-typings/src/v1/users.ts and other rest-typings files), keep the established convention of deriving field types from the domain model (e.g., use IUser indexed access like IUser['statusExpiresAt']) rather than swapping individual fields to serialized primitives (like string) in an ad-hoc way. If a truly different “serialized” representation is needed, perform the refactor consistently across the codebase (not just a single endpoint/field) and ensure all related REST typings stay aligned with the shared serialization types.
Applied to files:
packages/rest-typings/src/v1/licenses.ts
📚 Learning: 2025-12-10T21:00:43.645Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:43.645Z
Learning: Adopt the monorepo-wide Jest testMatch pattern: <rootDir>/src/**/*.spec.{ts,js,mjs} (represented here as '**/src/**/*.spec.{ts,js,mjs}') to ensure spec files under any package's src directory are picked up consistently across all packages in the Rocket.Chat monorepo. Apply this pattern in jest.config.ts for all relevant packages to maintain uniform test discovery.
Applied to files:
ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-02-24T19:22:48.358Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/omnichannel/omnichannel-send-pdf-transcript.spec.ts:66-67
Timestamp: 2026-02-24T19:22:48.358Z
Learning: In Playwright end-to-end tests (e.g., under apps/meteor/tests/e2e/...), prefer locating elements by translated text (getByText) and ARIA roles (getByRole) over data-qa attributes. If translation values change, update the corresponding test locators accordingly. Never use data-qa locators. This guideline applies to all Playwright e2e test specs in the repository and helps keep tests robust to UI text changes and accessible semantics.
Applied to files:
ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-03-06T18:10:15.268Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/code/CodeBlock.spec.tsx:47-68
Timestamp: 2026-03-06T18:10:15.268Z
Learning: In tests (especially those using testing-library/dom/jsdom) for Rocket.Chat components, the HTML <code> element has an implicit ARIA role of 'code'. Therefore, screen.getByRole('code') or screen.findByRole('code') will locate <code> elements even without a role attribute. Do not flag findByRole('code') as invalid in reviews; prefer using the implicit role instead of adding role="code" unless necessary for accessibility.
Applied to files:
ee/packages/license/src/validateLicenseForPreview.spec.ts
🔇 Additional comments (4)
.changeset/license-validate-preview.md (1)
1-8: LGTM!packages/core-typings/src/license/LicenseValidationResult.ts (1)
1-33: LGTM!packages/core-typings/src/license/index.ts (1)
11-11: LGTM!packages/rest-typings/src/v1/licenses.ts (1)
1-1: LGTM!Also applies to: 39-55, 66-68
| public async validateLicenseForPreview(encryptedLicense: string): Promise<LicenseValidationResult> { | ||
| const workspaceUrl = this.getWorkspaceUrl(); | ||
|
|
||
| let license: ILicenseV3; | ||
| try { | ||
| await validateFormat(encryptedLicense); | ||
|
|
||
| const decrypted = JSON.parse(await decrypt(encryptedLicense)); | ||
| license = encryptedLicense.startsWith('RCV3_') ? decrypted : convertToV3(decrypted); | ||
| } catch (err) { | ||
| logger.error({ msg: 'Invalid license provided for validation preview', err }); | ||
| return { | ||
| isFormatValid: false, | ||
| isValid: false, | ||
| workspaceUrl, | ||
| grantedModules: [], | ||
| validationErrors: [], | ||
| }; | ||
| } | ||
|
|
||
| // Run the full validation pipeline against the current workspace state. Unlike `validateLicense`, | ||
| // this does not store the license, change validity, replace modules/tags nor emit events. | ||
| // In addition to the behaviors that determine installation, also surface `prevent_action` so the | ||
| // preview can report limits that are already exceeded by the current workspace. | ||
| const validationResult = await runValidation.call(this, license, { | ||
| behaviors: [...licenseValidationBehaviors, 'prevent_action'], | ||
| isNewLicense: true, | ||
| suppressLog: true, | ||
| }); |
There was a problem hiding this comment.
Mirror the apply-path readiness guard before running preview validation.
setLicense() on Line 400 and validateLicense() on Line 275 both stop when isReadyForValidation.call(this) is false, but validateLicenseForPreview() goes straight into runValidation(). That lets the preview endpoint validate against partial workspace state instead of matching the apply path.
Suggested fix
public async validateLicenseForPreview(encryptedLicense: string): Promise<LicenseValidationResult> {
+ if (!isReadyForValidation.call(this)) {
+ throw new NotReadyForValidation();
+ }
+
const workspaceUrl = this.getWorkspaceUrl();🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@ee/packages/license/src/license.ts` around lines 333 - 361,
validateLicenseForPreview currently skips the readiness guard and calls
runValidation on partial workspace state; add the same readiness check used in
setLicense/validateLicense by calling isReadyForValidation.call(this) before
invoking runValidation and, if it returns false, short-circuit and return a
LicenseValidationResult matching the other guards (e.g., isFormatValid:
true/false per existing logic, isValid: false, workspaceUrl, empty
grantedModules and validationErrors) so the preview mirrors the apply-path
readiness behavior; reference validateLicenseForPreview, isReadyForValidation,
runValidation, setLicense and validateLicense when making the change.
There was a problem hiding this comment.
1 issue found across 7 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="ee/packages/license/src/license.ts">
<violation number="1" location="ee/packages/license/src/license.ts:357">
P2: Missing `isReadyForValidation` guard before calling `runValidation`. Both `validateLicense()` and `setLicense()` check `isReadyForValidation.call(this)` and throw `NotReadyForValidation` when the workspace isn't fully configured (e.g., workspace URL not yet set). Without the same guard here, the preview endpoint can validate against incomplete state and return misleading results. Add the readiness check (returning an appropriate error in the result) before running validation.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| // this does not store the license, change validity, replace modules/tags nor emit events. | ||
| // In addition to the behaviors that determine installation, also surface `prevent_action` so the | ||
| // preview can report limits that are already exceeded by the current workspace. | ||
| const validationResult = await runValidation.call(this, license, { |
There was a problem hiding this comment.
P2: Missing isReadyForValidation guard before calling runValidation. Both validateLicense() and setLicense() check isReadyForValidation.call(this) and throw NotReadyForValidation when the workspace isn't fully configured (e.g., workspace URL not yet set). Without the same guard here, the preview endpoint can validate against incomplete state and return misleading results. Add the readiness check (returning an appropriate error in the result) before running validation.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At ee/packages/license/src/license.ts, line 357:
<comment>Missing `isReadyForValidation` guard before calling `runValidation`. Both `validateLicense()` and `setLicense()` check `isReadyForValidation.call(this)` and throw `NotReadyForValidation` when the workspace isn't fully configured (e.g., workspace URL not yet set). Without the same guard here, the preview endpoint can validate against incomplete state and return misleading results. Add the readiness check (returning an appropriate error in the result) before running validation.</comment>
<file context>
@@ -312,6 +322,59 @@ export abstract class LicenseManager extends Emitter<LicenseEvents> {
+ // this does not store the license, change validity, replace modules/tags nor emit events.
+ // In addition to the behaviors that determine installation, also surface `prevent_action` so the
+ // preview can report limits that are already exceeded by the current workspace.
+ const validationResult = await runValidation.call(this, license, {
+ behaviors: [...licenseValidationBehaviors, 'prevent_action'],
+ isNewLicense: true,
</file context>
Adds a new
POST /api/v1/licenses.validateREST endpoint that validates a Rocket.Chat license (V2 or V3 JWT) against the current workspace's validation structure without applying it, so the result can be previewed from the UI before the license is committed.LicenseValidationResulttypeLicenseManager.validateLicenseForPreview()runs the same validation pipeline used on apply (URL, periods, limits) without mutating state or emitting events; the sharedlicenseValidationBehaviorsconstant is reused by both the apply and preview paths to avoid duplicationisLicensesValidatePropsschema + endpoint typinglicenses.validateroute (edit-privileged-setting)Proposed changes (including videos or screenshots)
Issue(s)
Steps to test or reproduce
Further comments
CORE-2104
Summary by CodeRabbit